
// 补零函数，将数字转换为指定位数的字符串，不足则前面补零
function padZero(num, length = 2) {
    return (Array(length).join('0') + num).slice(-length);
}

function formatDate(date, format) {
    const map = {
      'Y': date.getFullYear(),
      'm': padZero(date.getMonth() + 1),
      'd': padZero(date.getDate()),
      'H': padZero(date.getHours()),
      'i': padZero(date.getMinutes()),
      's': padZero(date.getSeconds()),
      'u': padZero(date.getMilliseconds(), 6)
    };

    return format.replace(/([YmdHisu])/g, (_, $1) => {
      return map[$1];
    });
}

function getRandomInt(n) {
    let result = '';
    for (let i = 0; i < n; i++) {
      result += Math.floor(Math.random() * 10); // 生成0-9之间的随机数
    }
    return result;
}

// 得到一个唯一值，可用于订单等，此接口可视化强，出现相同值的情况可忽略
// 标识(4位) 20180105 231106 013118(20位) 随机数字(8位) 补全到32位
function uniqid(flag = 1000) {
    const now = new Date();
    let id = formatDate(now, 'YmdHisu');
    id = `${flag}${id}`;

    let diff = 32;
    if (id.length < diff) {
        id = id + getRandomInt(diff - id.length);
    }
    return id;
}

function getUrlParams(url) {
  var params = {}
  var queryString = url.split('?')[1]

  if (queryString) {
    var keyValuePairs = queryString.split('&')

    for (var i = 0; i < keyValuePairs.length; i++) {
      var keyValuePair = keyValuePairs[i].split('=')
      var key = decodeURIComponent(keyValuePair[0])
      var value = decodeURIComponent(keyValuePair[1] || '')

      params[key] = value
    }
  }

  return params
}

export default {
    uniqid,
    formatDate,
    getRandomInt,
    getUrlParams
}
